/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */

package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;

import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilDevice;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseTopActivity;
import com.simon.mengkou.R;
import com.simon.mengkou.data.enums.ESmsType;
import com.simon.mengkou.future.base.OuerException;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.utils.UtilOuer;
import com.simon.mengkou.utils.UtilValidate;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * @author : Zhenshui.Xia
 * @date   :  2015-4-23
 * @desc   : (注册or忘记密码）手机号码获取界面
 */
public class UserPhoneActivity extends BaseTopActivity {
	//注册：1，忘记密码：2
	private int mType;

	//手机号码
	@Bind(R.id.phone_id_phone)
	EditText mEtPhone;
	//验证码
	@Bind(R.id.phone_id_code)
	EditText mEdtCode;
	//获取验证码，验证码有效剩余时间
	@Bind(R.id.phone_id_code_time)
	Button mTvCodeTime;
	//下一步
	@Bind(R.id.phone_id_next)
	Button mBtnNext;
	//定时任务
  	private AgnettyFuture mTimerFuture;
  	
	@Override
	protected void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		mType = getIntent().getIntExtra(CstOuer.KEY.TYPE, ESmsType.SMS_TYPE_REGISTER);
	}
	
	@Override
	protected void initTop() {
		setNavigation(R.drawable.common_ic_left_nav);
		if(mType == ESmsType.SMS_TYPE_REGISTER) {
			setTitle(R.string.user_register);
		} else {
			setTitle(R.string.user_pwd_forget);
		}
	}

	@Override
	protected void initLayout() {
		setContentView(R.layout.activity_user_phone);
	}

	@Override
	protected void initViews() {
		ButterKnife.bind(this);

		final int width = UtilDevice.getDevice(this).getWidth();
		final int height = (int)(56 * UtilDevice.getDevice(this).getDensity());

		mBtnNext.getViewTreeObserver().addOnGlobalLayoutListener(
				new ViewTreeObserver.OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				Rect rect = new Rect();
				mBtnNext.getWindowVisibleDisplayFrame(rect);
				mBtnNext.layout(0,
						rect.bottom - rect.top - 2 * height,
						width,
						rect.bottom - rect.top - height);
			}
		});

		registerAction(CstOuer.BROADCAST_ACTION.LOGINED_ACTION);
		registerAction(CstOuer.BROADCAST_ACTION.FORGET_PWD_ACTION);
	}


	@OnClick(R.id.phone_id_code_time)
	public void getSmsCode() {
		final String phone = mEtPhone.getText().toString().trim();
		//手机号码不能为空
        if(UtilString.isBlank(phone)) {
            UtilOuer.toast(this, R.string.user_phone_empty);
            mEtPhone.requestFocus();
            return;
        }
		//手机号码错误
        if(!UtilValidate.isPhone(phone)) {
			UtilOuer.toast(this, R.string.user_phone_error);
            mEtPhone.requestFocus();
            return;
        }


		final AgnettyFuture future = OuerApplication.mOuerFuture.phoneValidate(
				new OuerFutureListener(this){
					@Override
					public void onStart(AgnettyResult result) {
						super.onStart(result);
						setWaitingDialog(true);
					}

					@Override
					public void onComplete(AgnettyResult result) {
						super.onComplete(result);
						getSmsCode2(phone);
					}

					@Override
					public void onException(AgnettyResult result) {
						super.onException(result);
						setWaitingDialog(false);
						UtilOuer.toast(UserPhoneActivity.this, R.string.user_sms_code_failure);
					}

					@Override
					public void onNetUnavaiable(AgnettyResult result) {
						super.onNetUnavaiable(result);
						setWaitingDialog(false);
						UtilOuer.toast(UserPhoneActivity.this, R.string.user_sms_code_failure);
					}
				});

		attachDestroyFutures(future);
	}

	private void getSmsCode2(final String phone) {
		AgnettyFuture future = OuerApplication.mOuerFuture.getSmsCode(
				phone, mType,
				new OuerFutureListener(this) {
					@Override
					public void onStart(AgnettyResult result) {
						super.onStart(result);

					}

					@Override
					public void onComplete(AgnettyResult result) {
						super.onComplete(result);
						setWaitingDialog(false);
						UtilOuer.toast(UserPhoneActivity.this, getString(R.string.user_sms_code_tip, phone));
						startTimer();
					}

					@Override
					public void onException(AgnettyResult result) {
						super.onException(result);
						setWaitingDialog(false);

						mTvCodeTime.setText(R.string.user_get_sms_code);
						mTvCodeTime.setEnabled(true);
						cancelTimer();

						Exception ex = result.getException();
						if(ex instanceof OuerException) {
							UtilOuer.toast(UserPhoneActivity.this, ex.getMessage());
						}else {
							UtilOuer.toast(UserPhoneActivity.this, R.string.user_sms_code_failure);
						}
					}

					@Override
					public void onNetUnavaiable(AgnettyResult result) {
						super.onNetUnavaiable(result);
						setWaitingDialog(false);

						mTvCodeTime.setText(R.string.user_get_sms_code);
						mTvCodeTime.setEnabled(true);
						cancelTimer();

					}

				});

		attachDestroyFutures(future);
	}


	@Override
	public void onReceive(Intent intent) {
		super.onReceive(intent);
		//收到登录或忘记密码修改的广播后销毁界面
		String action = intent.getAction();
		if(CstOuer.BROADCAST_ACTION.LOGINED_ACTION.equals(action)
				|| CstOuer.BROADCAST_ACTION.FORGET_PWD_ACTION.equals(action)) {
			finish();
		}
	}


	/**
	 * 下一步：设置密码
	 */
	@OnClick(R.id.phone_id_next)
	public void next() {
		//手机号码
		final String phone = mEtPhone.getText().toString().trim();
		if(UtilString.isBlank(phone)) {
			UtilOuer.toast(this, R.string.login_phone_empty);
			mEtPhone.requestFocus();
			return;
		}

		if(!UtilValidate.isPhone(phone)) {
			UtilOuer.toast(this, R.string.login_phone_error);
			mEtPhone.requestFocus();
			return;
		}

		//验证码
		final String code =mEdtCode.getText().toString().trim();
		if(UtilString.isBlank(code)) {
			UtilOuer.toast(this, R.string.user_sms_code_empty);
			mEdtCode.requestFocus();
			return;
		}

		//校验验证码
//		AgnettyFuture future = OuerApplication.mOuerFuture.verifySmsCode(
//				phone, code, mType,
//				new OuerFutureListener(this) {
//			@Override
//			public void onStart(AgnettyResult result) {
//				super.onStart(result);
//				setWaitingDialog(true);
//			}
//
//			@Override
//			public void onComplete(AgnettyResult result) {
//				super.onComplete(result);
//				setWaitingDialog(false);
//				OuerDispatcher.presentUserPwdActivity(UserPhoneActivity.this, mType, phone, code);
//			}
//
//			@Override
//			public void onException(AgnettyResult result) {
//				super.onException(result);
//				setWaitingDialog(false);
//
//				Exception ex = result.getException();
//				if(ex instanceof OuerException) {
//					UtilOuer.toast(UserPhoneActivity.this, ex.getMessage());
//				}else {
//					UtilOuer.toast(UserPhoneActivity.this, R.string.user_sms_code_verify_failure);
//				}
//			}
//
//			@Override
//			public void onNetUnavaiable(AgnettyResult result) {
//				super.onNetUnavaiable(result);
//				setWaitingDialog(false);
//			}
//
//		});
//
//		attachDestroyFutures(future);

		OuerDispatcher.presentUserPwdActivity(this, mType, phone, code);
	}
	
	/**
	 * 定时
	 */
	private void startTimer() {
		mTvCodeTime.setEnabled(false);
		mTvCodeTime.setTag(60);
		mTimerFuture = OuerApplication.mOuerFuture.schedule(0, 1000, 61,
				new OuerFutureListener(this) {

			@Override
			public void onComplete(AgnettyResult result) {
				super.onComplete(result);
				int time = (Integer) mTvCodeTime.getTag();
				if (time == 0) {
					mTvCodeTime.setText(R.string.user_get_sms_code);
					mTvCodeTime.setEnabled(true);
					mTvCodeTime.setTag(60);
				} else {
					mTvCodeTime.setText(getString(R.string.user_get_sms_counter, time));
					mTvCodeTime.setTag(--time);
				}
			}
		});

		attachDestroyFutures(mTimerFuture);
	}
	
	/**
	 * 取消定时
	 */
	private void cancelTimer() {
		if(mTimerFuture != null) {
			mTimerFuture.cancel();
		}
	}
	
}
